package middlewares

import (
	"bytes"
	"gitee.com/zjlsliupei/ghelp"
	"github.com/gin-gonic/gin"
	"go-web/utils/alilog"
	"io/ioutil"
	"strconv"
	"time"
)

// RequestLog http请求日志中间件
func RequestLog(projectName, logStoreName, topic string) gin.HandlerFunc {
	return func(c *gin.Context) {
		runStart := time.Now()
		body, _ := c.GetRawData()
		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
		logData := map[string]string{
			"runMode": "dev",
			"ip":      c.ClientIP(),
			"body":    string(body),
			"uri":     c.Request.RequestURI,
			"method":  c.Request.Method,
		}
		// 处理请求
		c.Next()
		logData["http_status"] = strconv.FormatInt(int64(c.Writer.Status()), 10)
		json, exist := c.Get("json")
		if exist {
			logData["response_body"] = ghelp.JsonEncode(json)
		} else {
			logData["response_body"] = ""
		}
		logData["run_time"] = strconv.FormatInt(time.Since(runStart).Milliseconds(), 10)
		alilog.Record(projectName, logStoreName, topic, logData)
	}
}
